import md5 from 'md5';
var qs = require('qs');
// import AMap from 'AMap'; // 引入高德地图
export const randomWord = (randomFlag, min, max) => {
    var str = "",
        range = min,
        pos = "",
        arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

    // 随机产生
    if(randomFlag){
        range = Math.round(Math.random() * (max-min)) + min;
    }
    for(var i=0; i<range; i++){
        pos = Math.round(Math.random() * (arr.length-1));
        str += arr[pos];
    }
    return str;
}
// const md5 = require('md5')
// const qs = require('querystring')
export const ToUrlParams = (obj) => {
    let string = ''
    for (let k in obj) {
        if (k!=="sign" && obj[k] !== '' && !Array.isArray(obj[k])) {
            string += `${k}=${obj[k]}&`
        }
    }
    let result = string.replace(/(^&*)|(&*$)/g, "")
    return result
}
export const getSign = (data, {appid, appsecret, noncestr, timestamp, method='POST', key="yxp"}) => {
    let obj = {
        appid, appsecret, noncestr, method, timestamp, ...data
    }
    const ordered = {};
    Object.keys(obj).sort().forEach(function(key) {
      ordered[key] = obj[key];
    });
    let querystring = ToUrlParams(ordered)
    let result = `${querystring}${key}`
    let sign = md5(result)
    sign = sign.toUpperCase()
    return sign
}

export const getQueryString = (name) => {
    let reg = `(^|&)${name}=([^&]*)(&|$)`
    let r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

export const isClient = () => {
    return !!window.require && !!window.require('electron')
}

export const openBrowser = (url) => {
  if (isClient()) {
    window.require('electron').shell.openExternal(url)
  } else {
    window.open(url)
  }
}

export const fix = (num, length = 2) => {
    return ('' + num).length < length ? ((new Array(length + 1)).join('0') + num).slice(-length) : '' + num;
}

export const formatSeconds = (value, splits = []) => {
    var theTime = parseInt(value);// 需要转换的时间秒
    var theTime1 = 0;// 分
    var theTime2 = 0;// 小时
    var theTime3 = 0;// 天
    if(theTime > 60) {
        theTime1 = parseInt(theTime/60);
        theTime = parseInt(theTime%60);
        if(theTime1 > 60) {
            theTime2 = parseInt(theTime1/60);
            theTime1 = parseInt(theTime1%60);
            if(theTime2 > 24){
                //大于24小时
                theTime3 = parseInt(theTime2/24);
                theTime2 = parseInt(theTime2%24);
            }
        }
    }
    var result = '';
    result = ""+fix(parseInt(theTime))+(splits[0]||'秒');
    if(1 || theTime1 > 0 || (theTime2 > 0 || theTime3 > 0)) {
        result = ""+fix(parseInt(theTime1))+(splits[1]||'分')+result;
    }
    if(theTime2 > 0 || (theTime3 > 0)) {
        result = ""+fix(parseInt(theTime2))+(splits[2]||'小时')+result;
    }
    if(theTime3 > 0) {
        result = ""+parseInt(theTime3)+(splits[3]||'天')+result;
    }
    return result;
}

export const enterRoom = (data, that) => {
    // 是不是 pad  0 不是  1 是 （pad 一对一）
    let { course_channel, url } = data;
    // 0 一对一 1小班课
    // 1 有视频  0 无视频
    let { class_type, has_flow, pre_out_class } = data.config;
    let query = {};
    data.room_id && (query.room_id = data.room_id);
    data.prefixname && (query.prefixName = data.prefixname)
    data.partner_key && (query.partner_key = data.partner_key)
    data.sign && (query.sign = data.sign)
    pre_out_class && (query.pre_out_class = pre_out_class)
  query.doubleminus = sessionStorage.getItem("student_doubleminus");
  if(data.timecleandown != undefined) query.after_out_time = data.timecleandown
  if(data.timeenddown != undefined) query.work_end_time = data.timeenddown
    // 单PAD
    if (has_flow == 0) {
        query.class_mode = 'PAD_SINGLE'
        window.location.href = `${process.env.VUE_APP_PADURL}?${qs.stringify(query)}`;
        return false;
    }
    // 大班
    if(+class_type === 2){
        window.open(url)
        return false
    }
    // 小班、121
    +course_channel !== 0 && (query.has_pad = 1);
    +class_type === 0
    ? (query.class_mode = "PAD_121")
    : (query.class_mode = "PAD_SMALL");
    window.location.href = `?${qs.stringify(query)}#/room`;
}
export const enterdoubleRoom = (data, that) => {
  let query = {};
  query.class_mode = 'PAD_SINGLE'
  query.doubleminus = sessionStorage.getItem("student_doubleminus");
  if(data != undefined) query.after_out_time = data.timecleandown
  if(data != undefined) query.work_end_time = data.timeenddown
  window.location.href = `${process.env.VUE_APP_PADURL}?${qs.stringify(query)}`;
  return false;
}
//利用高德地图获取经纬度
export const getPosition = () => {
  return new Promise((resolve, reject) => {
      var geolocation = new BMap.Geolocation();
      // 开启SDK辅助定位
      geolocation.enableSDKLocation();
      geolocation.getCurrentPosition(function(res) {
     　　　if (res.latitude == null) {         　　
    　　　　　alert("定位失败,请开启定位！");
            //用户拒绝地理位置授权
            return;
          }else{
            var data = {
              'lat': res.latitude,
              'lon': res.longitude
            };
            console.log(data)
             resolve(data);
          }
      });
    // var map, geolocation;
    // //加载地图，调用浏览器定位服务   高德地图
    // map = new AMap.Map('container', {
    //   resizeEnable: true
    // });
    // map.plugin('AMap.Geolocation', function() {
    //   geolocation = new AMap.Geolocation({
    //     enableHighAccuracy: true, //是否使用高精度定位，默认:true
    //     timeout: 50000, //超过10秒后停止定位，默认：无穷大
    //     buttonPosition: 'RB'
    //   });
    //   geolocation.getCurrentPosition();
    //   AMap.event.addListener(geolocation, 'complete', function onComplete(data) {
    //     var getLongitude = data.position.getLng();
    //     var getLatitude = data.position.getLat();
    //     var data = {
    //       'lat': getLatitude,
    //       'lon': getLongitude
    //     };
    //     resolve(data);
    //   }); //返回定位信息

    //   AMap.event.addListener(geolocation, 'error', function onError(data) {
    //     console.log(data,'error');

    //   }); //返回定位信息
    // });
  })
}

export const __delay__ = (time) => {
    return new Promise((resolve) => setTimeout(resolve, time));
}

export const __waitForSync__ = async () => {
    let ifwin = document.getElementById('pad-frame').contentWindow
    try{
        window.__syncLock__ = true
        while(ifwin.__recvQueue__.length > 0){
            console.log('has opration no consumer', new Date().getTime())
            await __delay__(1000)
        }
    }catch(e){
        console.log('window.__syncLock__.error', e)
    }
    window.__syncLock__ = false
}
